package wassalt.client;

import static wassalt.Utils.AppConstants.HTTP_RESPONSE;
import static wassalt.Utils.AppConstants.HTTP_STATUS;
import static wassalt.Utils.AppConstants.URL;

import java.net.URLEncoder;

import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;

import wassalt.Services.HTTPService;
import wassalt.Utils.AppConstants;
import wassalt.Utils.Util;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;

public class CreateRequest extends CreateNotification {

	final String NewRequest_PATH = "/ManageNotifications/NewNotification_Generic";
	ProgressDialog dialog;
	String TAG = "CreateRequest";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		TextView header = (TextView) findViewById(R.id.title);
		header.setText(R.string.request_title);

		Button request = (Button) findViewById(R.id.done);
		request.setText(R.string.request_button);

		MultiAutoCompleteTextView contact = (MultiAutoCompleteTextView) findViewById(R.id.AddContact);
		contact.setHint(R.string.request_contact_hint);

	}

	/**
	 * @author Emy this method overrides the one in CreateNotification. Its main
	 *         goal is to insert the user's data of the request Notification in
	 *         the database. The function that will be used for insertion is in
	 *         'ManageNotifications' and is called "newNotification_generic".
	 *         The input is given to the function using ".putExtras". If one of
	 *         the chosen contacts are not registered to the application the
	 *         user will be notified
	 */
	@Override
	protected void insertDB(long userId, String phone, String place,
			boolean type, int when) {

		dialog = ProgressDialog.show(CreateRequest.this, "",
				getString(R.string.request_load_msg), true, false);

		Util.setConnecting(this, AppConstants.REQUEST_CON_KEY);

		// setting lel connection
		Intent offerServiceIntent = new Intent(this, HTTPService.class);
		offerServiceIntent.setAction(AppConstants.HTTP_INSERT_REQUEST_FILTER);
		offerServiceIntent.putExtra(URL, getString(R.string.server_url)
				+ NewRequest_PATH);

		// Loai code "to be approved by Aya
		boolean debug = false;
		if (!debug) {
			offerServiceIntent.putExtra("ntype", AppConstants.REQUEST);
			offerServiceIntent.putExtra("idOwner", currentUserId);
			offerServiceIntent.putExtra("phoneSender",
					URLEncoder.encode(phoneReceiversJson.toString()));
			offerServiceIntent.putExtra("jsonString", getData().toString());
			startService(offerServiceIntent);
		} else {
			// newNotification(int ntype,long idOwner, String phoneSender,
			// String
			// place, boolean type, int when)
			offerServiceIntent.putExtra("ntype", AppConstants.REQUEST);
			offerServiceIntent.putExtra("idOwner", currentUserId);
			offerServiceIntent.putExtra("phoneSender", phoneReceivers);
			offerServiceIntent.putExtra("place", place);
			offerServiceIntent.putExtra("type", type);
			offerServiceIntent.putExtra("when", when);
			// if statement to contain el start and end date
			startService(offerServiceIntent);
		}
	}

	/**
	 * @author Emy a broadcastreceiver that will handle the reply from the
	 *         server
	 */
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent requestIntent) {
			try {

				Log.d(TAG, "Resposnse from request service arrived");
				// updating UI according to response
				int http_status = requestIntent.getExtras().getInt(HTTP_STATUS);

				if (http_status == HttpStatus.SC_OK) {
					Log.d(TAG, "Connecting");

					String temp = requestIntent.getExtras().getString(
							HTTP_RESPONSE);

					Log.d(TAG, "Connecting:" + temp);
					Util.setDisconnecting(CreateRequest.this,
							AppConstants.REQUEST_CON_KEY, temp);
					handleSuccess(temp);

				} else {
					Log.d(TAG, "Not Created!");
					throw new Exception();
				}

			} catch (Exception e) {
				Log.d(TAG, "Catching exception");
				dialog.dismiss();
				Util.setDisconnecting(CreateRequest.this,
						AppConstants.REQUEST_CON_KEY, "" + AppConstants.FAILURE);
				handleFailure();
			} finally {
				dialog.dismiss();
			}

		}
	};

	/**
	 * @author Emy Register the broadcast receiver with each onResume, if not
	 *         connecting and handle the extras sent if any
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppConstants.HTTP_INSERT_REQUEST_FILTER);
		registerReceiver(receiver, filter);
		if (!Util.isConnecting(this, AppConstants.REQUEST_CON_KEY)) {
			registerReceiver(receiver, filter);
			if (dialog != null)
				dialog.dismiss();
			if (Util.getExtra(this, AppConstants.REQUEST_CON_KEY) != null) {
				if (Util.getExtra(this, AppConstants.REQUEST_CON_KEY).equals(
						"" + AppConstants.FAILURE))
					handleFailure();
				else
					handleSuccess(Util.getExtra(this,
							AppConstants.REQUEST_CON_KEY));
			}
		}
	}

	/**
	 * @author Emy UnRegister the broadcast receiver with each onPause, if not
	 *         connecting
	 */
	@Override
	protected void onPause() {
		super.onPause();
		if (!Util.isConnecting(this, AppConstants.REQUEST_CON_KEY)) {
			unregisterReceiver(receiver);
			Util.clearConnection(this, AppConstants.REQUEST_CON_KEY);
		}
	}

	/**
	 * @author Emy this method is called when the status of the server returns
	 *         success. Then, an alert window is displayed with the phone
	 *         numbers of the unregistered users to notify the user that the
	 *         request cannot be sent to them. Last, the user in this case
	 *         is returned back to the NotificationsListActivity
	 */
	private void handleSuccess(String response) {
		String notRegisteredUsers = "";
		String[] phoneRecv = phoneReceivers.split(";");
		boolean oneContact = true;

		JSONArray isRegistered = null;
		try {
			isRegistered = new JSONArray(response);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		for (int i = 0; i < isRegistered.length(); i++) {
			try {
				if (!isRegistered.getBoolean(i)) {
					if (notRegisteredUsers.equals(""))
						notRegisteredUsers = phoneRecv[i];
					else {
						notRegisteredUsers = notRegisteredUsers + ", "
								+ phoneRecv[i];
						oneContact = false;
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (!notRegisteredUsers.equalsIgnoreCase("")) {
			AlertDialog window = new AlertDialog.Builder(CreateRequest.this)
					.create();
			if (oneContact)
				window.setMessage(getString(R.string.no_reg_msg)
						+ notRegisteredUsers);
			else
				window.setMessage(getString(R.string.no_reg_msg_2)
						+ notRegisteredUsers);
			window.setButton("OK", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					Intent returnToActivity = new Intent();
					returnToActivity.setClass(getApplicationContext(),
							NotificationsListActivity.class);
					startActivity(returnToActivity);
				}
			});
			window.show();
		} else {
			Intent returnToActivity = new Intent();
			returnToActivity.setClass(getApplicationContext(),
					NotificationsListActivity.class);
			startActivity(returnToActivity);
		}
	}

	/**
	 * @author Emy this method is called when the status from the server is
	 *         failure of an exception occured where an alertwindow is displayed
	 *         to notify the user that an error occured
	 */
	private void handleFailure() {
		AlertDialog window = new AlertDialog.Builder(CreateRequest.this)
				.create();
		window.setMessage(getString(R.string.error_toast));
	}
}